package com.bbs.listener;


import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;

import com.bbs.dao.SectionDao;
import com.bbs.dao.impl.SectionDaoImpl;
import com.bbs.dao.impl.UserDaoImpl;
import com.bbs.model.Section;
import com.bbs.model.User;
import com.bbs.util.LogUtil;

public class ContextListener implements ServletContextListener {
	
	private static Logger log = null;
	 ServletContext servletContext=null;
	
	//这个方法在Web应用服务被移除，没有能力再接受请求的时候被调用
	public void contextDestroyed(ServletContextEvent sce) {

	}
	
	//xf：这个方法在Web应用服务做好接受请求的时候被调用
	public void contextInitialized(ServletContextEvent sce) {
		ServletContext servletContext=sce.getServletContext();
		new LogUtil().initializeLogger();
		log = Logger.getLogger(ContextListener.class);
		setContextData(servletContext);
		log.info("context init-------");
	}

	private void setContextData(ServletContext servletContext) {
		setUserCahe(servletContext);
		setSectionCahe(servletContext);
		log.info("setContextData done-------");
		
		
	}
	//把用户放到application里面
	public void setUserCahe(ServletContext servletContext){
		try {
			UserDaoImpl userDao = null;
			userDao = new UserDaoImpl();
			List<User> userList=userDao.listUser();
			Map<Integer, User> userCache=new HashMap<Integer, User>();
			for(User user:userList){
				userCache.put(user.getUser_id(), user);
			}
			servletContext.setAttribute("userCache", userCache);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//把板块放到application里面
	public void setSectionCahe(ServletContext servletContext){
		try {
			SectionDao sectionDao;
			List<Section> sectionList;
			sectionDao=new SectionDaoImpl();
			sectionList=sectionDao.findAll();
			Map<Integer, Section> userCache=new HashMap<Integer,Section>();
			for(Section section:sectionList){
				userCache.put(section.getSection_id(), section);
			}
			servletContext.setAttribute("sectionCache", userCache);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		log.info("setSetionCache-------");
	}
	
	
  
}

